<?php
/**
 * erp model类
 * Created by PhpStorm.
 * User: 章利桂
 * Date: 2016/9/7
 * Time: 11:48
 */
class adminErpModel
{
    const RACE = 1;//赛事
    const FLASHSHOP = 5;//闪购
    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
        $this->erpManageDb =  isset($this->base->erpManageDb) ? $this->base->erpManageDb : $this->base->in_db('erpManageDb');
    }
 /*****************************分类START**********************************/
    /**
     * 查询分类列表
     */
    public function getCategoryList($params) {
        $start    = $params['start'] ? (int)$params['start'] : 0;
        $limitNum = $params['limit'] ? (int)$params['limit'] : 10;
        $title = isset($params['name']) ? trim($params['name']) : '';
        $where = 'status=0';
        if ($title) {
            $where .=' and title like '."'%$title%'";
        }
        $sql ="select * from r_product_category where $where order by id desc limit $start,$limitNum";
        $cntsql ="select count(1) as cnt from r_product_category where $where";
        $this->total =  $this->erpManageDb->getOne("$cntsql");
        return $this->erpManageDb->getAll($sql);
    }

    /**
     * 分类添加
     */
    public function addCategory($id=0,$title) {
        if (!$id) {
            $create_time = time();
            $data = compact('title','create_time');
            $r =$this->erpManageDb->insertRow('r_product_category',$data,0);
            return $r;
        }
        $sql = "update r_product_category set title='$title' where id=$id";
        $r = $this->erpManageDb->update($sql);
        return $r;
    }

    /**
     * 分类是否存在
     */
    public function categoryIsExist($id=0,$name) {
        $where = 'title='."'$name'";
        if ($id) {
            $where .=' and id <>'.$id;
        }
        $sql = "select id from r_product_category where $where";
        return $this->erpManageDb->getOne($sql) ? true : false;
    }

    /**
     * 分类的货品数
     */
    public function getProductCntByCid(array $cid) {
        $strCid = implode(',',$cid);
        $sql = "SELECT category_id,count(1) AS cnt FROM r_product where category_id in($strCid) GROUP BY category_id";
        $list = $this->erpManageDb->getAll($sql);
        $result = [];
        $r = [];
        if ($list) {
            foreach($list as $k=>$v) {
                $r[$v['category_id']] = $v['cnt'];
            }
        }
        foreach($cid as $key=>$val) {
            if ($r && array_key_exists($val,$r)) {
                $result[$val] = $r[$val];
                continue;
            }
            $result[$val] = 0;
        }
        return $result;
    }

    /**
     * 查询所有分类
     */
    public function getCategoryListForSelect() {
        $sql ="select id,title from r_product_category where status=0";
        return $this->erpManageDb->getAll($sql);
    }

    /**
     * 分类Info
     */
    public function getCategoryInfo($id,$fields ='*') {
        $sql = "select $fields from r_product_category where id= $id";
        return $this->erpManageDb->getRow($sql);
    }

    /*****************************分类END**********************************/

    /*****************************物流START**********************************/
    /**
     * 查询物流
     */
    public function getLogisticsTepList($params) {
        $start    = $params['start'] ? (int)$params['start'] : 0;
        $limitNum = $params['limit'] ? (int)$params['limit'] : 10;
        $title = isset($params['name']) ? trim($params['name']) : '';
        $where = 'status=0';
        if ($title) {
            $where .=' and title like '."'%$title%'";
        }
        $sql ="select * from r_logistics where $where order by id desc limit $start,$limitNum";
        $cntsql ="select count(1) as cnt from r_logistics where $where";
        $this->total =  $this->erpManageDb->getOne("$cntsql");
        return $this->erpManageDb->getAll($sql);
    }

    /**
     * 物流添加
     */
    public function addLogisticsTep($id=0,$title) {
        if (!$id) {
            $create_time = time();
            $data = compact('title','create_time');
            $r =$this->erpManageDb->insertRow('r_logistics',$data,0);
            return $r;
        }

        $sql = "update r_logistics set title='$title' where id=$id";
        $r = $this->erpManageDb->update($sql);
        return $r;
    }

    /**
     * 物流是否存在
     */
    public function logisticsTepIsExist($id=0,$name) {
        $where = 'title='."'$name'";
        if ($id) {
            $where .=' and id <>'.$id;
        }
        $sql = "select id from r_logistics where $where";
        return $this->erpManageDb->getOne($sql) ? true : false;
    }

    /**
     * 物流Info
     */
    public function getlogisticsTepInfo($id,$fields ='*') {
        $sql = "select $fields from r_logistics where id= $id";
        return $this->erpManageDb->getRow($sql);
    }

    /**
     * 物流Info
     */
    public function getlogisticsTepInfoByName($title,$fields ='*') {
        $sql = "select $fields from r_logistics where title= '$title'";
        return $this->erpManageDb->getRow($sql);
    }
    /*****************************物流END**********************************/

    /*****************************货品START**********************************/
    /**
     * 查询货品列表
     */
    public function getProductList(array $params) {
        $start    = $params['start'] ? (int)$params['start'] : 0;
        $limitNum = $params['limit'] ? (int)$params['limit'] : 10;
        $title = isset($params['name']) ? trim($params['name']) : '';
        $code = isset($params['code']) ? trim($params['code']) : '';
        $status = isset($params['status']) ? (int)$params['status'] : 0;
        $categoryId = isset($params['cid']) ? (int)$params['cid'] : 0;
        $where = '1=1';
        if ($title) {
            $where .=' and title like '."'%$title%'";
        }
        if ($code) {
            $where .=' and code like '."'%$code%'";
        }
        if ($status) {
            if ($status == 1) {
                $where .= ' and status=0';
            } else if($status == 2) {
                $where .= ' and status=5';
            }
        }
        if ($categoryId) {
            $where .= ' and category_id='.$categoryId;
        }
        $sql ="select * from r_product where $where order by id desc limit $start,$limitNum";
        $cntsql ="select count(1) as cnt from r_product where $where";
        $this->total =  $this->erpManageDb->getOne("$cntsql");
        return $this->erpManageDb->getAll($sql);
    }

    /**
     * 添加货品
     */
    public function addErpProduct(array $params) {
        $code  = $this->generateProductCode();
        $title = $params['name'];
        $category_id = $params['category_id'];
        $image = $params['image'];
        $express_fee = $params['express_fee'];
        $image_num = $image ? count($image) : 0;
        $create_time = time();
        $data = compact('code','title','category_id','image_num','create_time','express_fee');
        $product_id = $this->erpManageDb->insertRow('r_product',$data,0);
        if ($product_id) {
            $str = '';
            if ($image_num > 0) {
                $i = 0;
                $image_2 = [];
                foreach($image as $k=>$v) {
                    $image_url = $v;
                    $imageData =  compact('product_id','image_url','create_time');
                    $r = $this->erpManageDb->insertRow('r_product_image',$imageData,0);
                    if ($r) {
                        $i++;
                        $image_2[] =$v;
                    }
                }
                $str = $i > 0 ? ($logMsg = ' 配图：'.implode(',',$image_2).', 共'.$i.'张' ) : '';
            }
            $this->addErpLog(1,$product_id,2,'添加了一个货品,货品ID为'.$product_id.',货品名称：'.$title.$str);
            return true;
        }
        return false;
    }
    
    public function updateErpProduct(array $params){
        if(!isset($params['id'])){
            return;
        }
        $row['id'] = $params['id'];
        if(isset($params['title'])) {
            $row['title'] = $params['title'];
        }
        if(isset($params['express_fee'])) {
            $row['express_fee'] = $params['express_fee'];
        }
        $product_id = $params['id'];
        $res = $this->erpManageDb->updateRowTable('r_product',$row);
        $this->addErpLog(2,$product_id,2,'更新货品'.$product_id);
        return $product_id;
    }

    /**
     * 生成货品code
     */
    public function generateProductCode() {
        $code = substr('P'.md5(microtime(true)),0,9);
        $sql = "select id from r_product where code = '$code'";
        $id = $this->erpManageDb->getOne($sql);
        if ($id) {
            return $this->generateProductCode();
        }
        return $code;
    }

    /**
     * 货品是否存在
     */
    public function productIsExist($id=0,$name) {
        $where = 'title='."'$name'";
        if ($id) {
            $where .=' and id <>'.$id;
        }
        $sql = "select id from r_product where $where";
        return $this->erpManageDb->getOne($sql) ? true : false;
    }

    /**
     * 货品Info
     */
    public function getProductInfo($id,$fields ='*') {
        $sql = "select $fields from r_product where id= $id";
        return $this->erpManageDb->getRow($sql);
    }

    /**
     * 货品Info By code
     */
    public function getProductInfoByCode($code,$fields ='*') {
        $sql = "select $fields from r_product where code= '$code'";
        return $this->erpManageDb->getRow($sql);
    }

    /**
     * 查询货品规格
     */
    public function getProductStandard($pid) {
        $sql = "select id,title,product_id from r_goodattr_head where product_id=$pid";
        $list = $this->erpManageDb->getAll($sql);
        $result =[];
        if (!$list) {
            return $result;
        }
//        array(
//            array(
//                'id'=>1,
//                'name'=>'headName',
//                'child'=>array(
//                    array('id'=>3,'name'=>'asdd') ,
//                    array('id'=>3,'name'=>'asdd')
//                )
//            ),
//            array(
//                'id'=>1,
//                'name'=>'headName',
//                'child'=>array(
//                    array('id'=>3,'name'=>'asdd') ,
//                    array('id'=>3,'name'=>'asdd')
//                )
//            )
//        ) ;
        foreach ($list as $k=>$v) {//获取属性值
            $list[$k]['id'] = $v['id'];
            $list[$k]['title'] = $v['title'];
            $list[$k]['product_id'] = $v['product_id'];
            $sql = "select * from r_goodattr_value where head_id=".$v['id'].' and status=0';
            $arrVal = $this->erpManageDb->getAll($sql);
            if (!$arrVal) {
                $list[$k]['child'] = [];
                return $list;
            }
            foreach ($arrVal as $k2=>$v2) {
                $list[$k]['child'][] = [
                 'id'=>$v2['id'],
                 'title'=>$v2['title'],
                 'img_source'=>$v2['img_source']
                ];
            }
        }
        return $list;
//
//        foreach ($list as $key=>$val) {
//            if (!array_key_exists($val['headId'],$result[$val['headId']])) {
//                $result[$val['headId']]['id'] = $val['headId'];
//                $result[$val['headId']]['name'] = $val['headName'];
//            }
//            $result[$val['headId']]['child'][] = array('id'=>$val['vid'],'name'=>$val['vName']);
//        }
//        return $result;
    }

    /**
     * 新加入库数量
     */
    public function addProductStockNum($pid,$num) {
        $sql = "update r_product set stock_into_num=stock_into_num+$num,real_stock_num=real_stock_num+$num where id=$pid";
        return  $this->erpManageDb->update($sql);
    }

    /**
     * 盘点更新 真实库存 数量
     */
    public function setProductRealStockNum($pid,$stockNum) {
        $sql = "update r_product set real_stock_num=$stockNum where id=$pid";
        return $this->erpManageDb->update($sql);
    }

    /**
     * 重新计算货品 真实库存
     */
    public function repeatProductRealStockNum($pid) {
        $totalRealCnt = $this->getStandGoodsRealStockNum($pid);
        return $this->setProductRealStockNum($pid,$totalRealCnt);
    }

    /**
     * 开售/停售
     */
    public function setProductStatus($pid,$status) {
        $sql = "update r_product set status=$status where id=$pid";
        return $this->erpManageDb->update($sql);
    }

    /**
     * 后台货品详情
     */
    public function getProductDetail($pid) {
        //货品基本信息
        $info = $this->getProductInfo($pid);
        if (!$info) return false;
        $arrCategoryList = $this->getCategoryListForSelect(); //查询分类
        foreach ($arrCategoryList as $k=>$v) {//优化
            if ($info['category_id'] == $v['id']) {
                $info['categoryName'] = $v['title'];
                break;
            }
        }
        //货品图片
        $info['imageList'] = $this->getProductImage($pid);
        //规格商品明细
        $sql = "select * from r_goods where product_id=$pid";
        $arrGoods = $this->erpManageDb->getAll($sql);
        $result = [];
        if ($arrGoods) {
            foreach($arrGoods as $key=>$val) {
                $result[$key]['gid'] = $val['id'];
                $result[$key]['attrPathName'] = $this->getAttrPathName($val['product_id'],$val['attr_path']);
                $result[$key]['stockIntoNum'] = $val['stock_into_num'];
                $result[$key]['realStockNum'] = $val['real_stock_num'];
            }
        }
        $info['childGoods'] = $result;
        $arrUser = [];//操作用户
        //入库明细
        $arrStockInto = $this->getStockIntoList($pid);
        $result = [];
        if ($arrStockInto) {
            foreach($arrStockInto as $key=>$val) {
                $arr = $this->getGoodsByGid($val['goods_id']);
                $result[$key]['attrPathName'] =$arr['attrPathName'];
                if (!array_key_exists($val['operate_uid'],$arrUser)) {
                    $hupuUser = $this->base->load('adminList')->getRowByHupuUid($val['operate_uid']);
                    $arrUser[$val['operate_uid']] = $hupuUser;
                }
                $result[$key]['operateName'] = isset($arrUser[$val['operate_uid']]['hupu_username']) ? $arrUser[$val['operate_uid']]['hupu_username'] : '' ;
                $result[$key]['formatTime'] = $val['create_time'] ? date('Y-m-d H:i:s',$val['create_time']) : '';
                $result[$key]['stockIntoNum'] = $val['stock_into_num'];
                $result[$key]['price'] = $val['price'];
            }
        }
        $info['arrStockIntoList'] = $result;
        //盘点明细
        $arrStockCheck = $this->getStockCheckList($pid);
        $result = [];
        if ($arrStockCheck) {
            foreach($arrStockCheck as $key=>$val) {
                $arr= $this->getGoodsByGid($val['goods_id']);
                $result[$key]['attrPathName'] = $arr['attrPathName'];
                if (!array_key_exists($val['operate_uid'],$arrUser)) {
                    $hupuUser = $this->base->load('adminList')->getRowByHupuUid($val['operate_uid']);
                    $arrUser[$val['operate_uid']] = $hupuUser;
                }
                $result[$key]['operateName'] = isset($arrUser[$val['operate_uid']]['hupu_username']) ? $arrUser[$val['operate_uid']]['hupu_username'] : '' ;
                $result[$key]['formatTime'] = $val['create_time'] ? date('Y-m-d H:i:s',$val['create_time']) : '';
                $result[$key]['currentStockNum'] = $val['current_stock_num']; //理论库存
                $result[$key]['realStockNum'] = $val['real_stock_num']; //实际库存
                $result[$key]['content'] = $val['content'];
            }
        }
        $info['arrStockCheckList'] = $result;

        return $info;
    }

    /**
     *  入库明细（作为新页面 以后必改）
     */
    public function getStockIntoList($pid) {
        $sql = "select * from r_stock_into_detail where product_id=$pid";
        return $this->erpManageDb->getAll($sql);
    }

    /**
     * 盘点明细 （作为新页面 以后必改）
     */
    public function getStockCheckList($pid) {
        $sql = "select * from r_stock_check_detail where product_id=$pid";
        return $this->erpManageDb->getAll($sql);
    }

    /**
     * 查询货品图片
     */
    public function getProductImage($pid) {
        $sql = "select * from r_product_image where product_id=$pid and status=0";
        $list = $this->erpManageDb->getAll($sql);
        return $list ? $list : [];
    }

    /**
     * 增加货品图片
     */
    public function addProductImage($product_id=0, $image_url='') {
        if (!$image_url) {
            return false;
        }
        if (!$product_id){
           return $image_url;
        }
        $create_time = time();
        $data = compact('product_id','image_url','create_time');
        $r = $this->erpManageDb->insertRow('r_product_image',$data,0);
        if ($r) {
            //增加货品图片数量
            $r2 = $this->erpManageDb->update("update r_product set image_num= image_num+1 where id = $product_id");
            return $image_url;
        }
        return false;
    }

    /**
     * 删除货品图片
     */
    public function delProductImages(array $imageId) {
        $strImagId = implode(',',$imageId);
//        $r = $this->erpManageDb->update("update r_product_image set status=-1 where id in($strImagId)");
        $rows = $this->erpManageDb->getAll("select id,image_url,product_id from r_product_image where id in($strImagId)");
        $ok = false;
        foreach($rows as $key=>$val) {
            $r = $this->erpManageDb->update("update r_product_image set status=-1 where id = {$val['id']}");
            if ($r) {//减少货品总图片数量，删除七牛图片
                 $ok = true;
                //货品信息
                $arrId = $this->getProductInfo($val['product_id'],'id');
                if($arrId) {
                    $r2 = $this->erpManageDb->update("update r_product set image_num= image_num-1 where id = {$arrId['id']}");
                }
                $this->base->load('qiniu')->batchDeleteImg(array($val['image_url']));
            }
        }
        return $ok;
    }

    /*****************************货品END**********************************/

    /*****************************规格START**********************************/
    /**
     * 查询规格名称信息
     */
    public function getStandHeadInfo($headId,$fields='*') {
        $sql = "select $fields from r_goodattr_head where id= $headId";
        return $this->erpManageDb->getRow($sql);
    }


    /**
     * 查询规格是否存在
     */
    public function standardIsExist($pid, $standardHeadName) {
        $sql = "select id from r_goodattr_head where product_id=$pid and title='$standardHeadName' and status=0";
        return $this->erpManageDb->getOne($sql) ? true :false;
    }

    /**
     * 查询规格值是否存在
     */
      public function standardValIsExist($headId,array $arrStandVal) {
          $strStandVal = '\''.implode('\',\'',$arrStandVal).'\'';
          $sql = "select * from r_goodattr_value where head_id=$headId and title in($strStandVal)";
          return $this->erpManageDb->getAll($sql);
      }

    /**
     * 写入规格名
     */
    public function addStandardHead($product_id, $title) {
        $create_time = time();
        $data = compact('title','product_id','create_time');
        return $this->erpManageDb->insertRow('r_goodattr_head',$data,0);
    }
    
    public function updateStandardHead($id, $title){
        $data = compact('id','title');
        return $this->erpManageDb->updateRowTable('r_goodattr_head',$data);
    }
    
    public function delStandardHead($id){
        if(!is_numeric($id)){
            return false;
        }
        return $this->erpManageDb->delDataTable('r_goodattr_head','id='.$id);
    }

    /**
     * 写入规格值
     */
    public function addStandVal($headId,$pid,$arrStandVal) {
        $head_id = $headId;
        $product_id = $pid;
        
        $title = $arrStandVal;
        if (!trim($title)){
            return false;
        }
        $create_time = time();
        $data = compact('head_id','product_id','create_time','title');
        return $this->erpManageDb->insertRow('r_goodattr_value',$data,0);
    }
    
    public function updateStandVal($data){
        if(!$data['id']){
            return false;
        }
        $row = ['id'=>$data['id']];
        isset($data['title']) && $row['title'] = $data['title'];
        isset($data['img_source']) && $row['img_source'] = $data['img_source'];
        return $this->erpManageDb->updateRowTable('r_goodattr_value',$row);
    }
    
    public function delStandardVal($id){
        if(!is_numeric($id)){
            return false;
        }
        return $this->erpManageDb->delDataTable('r_goodattr_value','id='.$id);
    }

    /**
     * 查询货品有几级规格
     */
    public function getProductHeadCnt($pid) {
        $sql = "select count(1) as cnt from r_goodattr_head where product_id=$pid and status=0";
        return $this->erpManageDb->getOne($sql);
    }

    /**
     * 查询所有货品值
     */
    public function getProductVal($pid,$fields='*') {
        $sql = "select $fields from r_goodattr_value where product_id=$pid and status=0";
        return $this->erpManageDb->getAll($sql);
    }

    /**
     * 查询一维数组所有货品值 array('id'=>'title')
     */
    public function getOneProductVal($pid) {
        $arrGoodsVal = $this->getProductVal($pid,'id,title');
        $arrOneGoodsVal = [];
        if ($arrGoodsVal) {
            foreach ($arrGoodsVal as $key=>$val) {
                $arrOneGoodsVal[$val['id']] = $val['title'];
            }
        }
        return $arrOneGoodsVal;
    }

    /**
     * 查询规格商品 属性关系路径 名称
     */
    public function getAttrPathName($pid,$strAttrPath) {
        $arrAttrPath = explode(',',$strAttrPath);
        $arrOneGoodsVal = $this->getOneProductVal($pid);//所有属性 格式：id=>val
        $arrAttrPathName = '';
        foreach($arrAttrPath as $key=>$val) {
            $arrAttrPathName[] = isset($arrOneGoodsVal[$val]) ? $arrOneGoodsVal[$val] : '';
        }
        return implode('—',$arrAttrPathName);
    }
    /**
     * 查询规格商品 属性关系路径 名称
     */
    public function getAttrPathId($pid,$strAttrPath) {
        $arrAttrPath = explode(',',$strAttrPath);
        $arrOneGoodsVal = $this->getOneProductVal($pid);//所有属性 格式：id=>val
        $arrAttrPathName = '';
        foreach($arrAttrPath as $key=>$val) {
            $arrAttrPathName[] = isset($arrOneGoodsVal[$val]) ? $val : '';
        }
        return implode('—',$arrAttrPathName);
    }
    /**
     * 查询规格商品 属性组合 {id:$id,name:$name}……
     * @param $pid
     * @param $strAttrPath
     * @return array
     */
    public function getMergeAttrList($pid,$strAttrPath) {
        $arrAttrPath = explode(',',$strAttrPath);
        $arrOneGoodsVal = $this->getOneProductVal($pid);//所有属性 格式：id=>val
        if (!$arrOneGoodsVal) return [];
        $arrAttr = [];
        foreach($arrAttrPath as $key=>$val) {
            $arrAttr[] =  isset($arrOneGoodsVal[$val]) ? array('id'=>$val,'name'=>$arrOneGoodsVal[$val]) : '';;
        }
        return $arrAttr;
    }

    /**
     *查询属性head名称,通过货品ID
     */
    public function getAttrheadNameByPid($pid) {
        return $this->erpManageDb->getAll("select id,title from r_goodattr_head where product_id=$pid");
    }

    /**
     * 查询所有属性,通过货品ID
     * @param $pid
     * @return array
     */
    public function getAllAttrByPid($pid) {
        $list = $this->erpManageDb->getAll("select id,head_id,title,img_source from r_goodattr_value where product_id=$pid");
        if (!$list) {
            return [];
        }
        $reault = [];
        foreach ($list as $key=>$val) {
            if(!array_key_exists($val['head_id'],$reault)) {
                $arrHeadInfo = $this->erpManageDb->getRow("select id,title from r_goodattr_head where id={$val['head_id']}");
                $reault[$val['head_id']]['headInfo'] = $arrHeadInfo ? $arrHeadInfo : [];
                $reault[$val['head_id']]['attrValue'] = [];
            }
            $reault[$val['head_id']]['attrValue'][] = array('id'=>$val['id'],'title'=>$val['title'],'img_source'=>$val['img_source']);
        }
        return $reault;
    }


    /*****************************规格END**********************************/

    /*****************************商品stard**********************************/
    /**
     * 规格商品Info
     */
    public function getGoodsInfo($id,$fields ='*') {
        $sql = "select $fields from r_goods where id= $id";
        return $this->erpManageDb->getRow($sql);
    }

    /**
     * 查询规格商品，条件：货品ID
     */
    public function getGoodsByPid($pid) {
        $sql = "select * from r_goods where product_id=$pid and status=0";
        $list = $this->erpManageDb->getAll($sql);
        foreach($list as $key=>$val) {
           $list[$key]['attrPathName'] = $this->getAttrPathName($val['product_id'],$val['attr_path']);
        }
        return $list;
    }

    /**
     * 查询规格商品，条件：商品ID
     */
    public function getGoodsByGid($gid) {
        $sql = "select * from r_goods where id=$gid and status=0";
        $info = $this->erpManageDb->getRow($sql);
        if (!$info) {
            return false;
        }
        $info['attrPathName'] = $this->getAttrPathName($info['product_id'],$info['attr_path']);
        return $info;
    }

    /**
     * 查询货品是否有规格商品
     */
    public function getGoodsIsExistByPid($pid) {
        $sql = "select id from r_goods where product_id=$pid";
        return $this->erpManageDb->getOne($sql) ? true : false;
    }

    /**
     * 查询货品是否存在某规格组合
     */
    public function getStrAttrIsExist($pid,$strAttr) {
        $sql = "select id from r_goods where product_id=$pid and attr_path='$strAttr'";
        return $this->erpManageDb->getOne($sql) ? true : false;
    }

    /**
     * 添加入库商品
     */
    public function addGoods(array $params) {
        $code = $this->generateGoodsCode();
        $create_time = time();
        $product_id = $params['product_id'];
        $attr_path = $params['attr_path'];
        $price = $params['price'];//后期算平均价
        $stock_into_num = $params['stockIntoCnt'];
        $real_stock_num = $params['stockIntoCnt'];
        $imageId = 0;//预留
        $data = compact('product_id','code','attr_path','stock_into_num','real_stock_num','create_time');
        $id = $this->erpManageDb->insertRow('r_goods',$data,0);
        if ($id) {//增加货品入库数量
             $this->addProductStockNum($product_id,$stock_into_num);
            //新增入库明细
             $this->addStockIntoDetail($product_id,$id,$stock_into_num,$price);
        }
        return $id;
    }

    /**
     * 生成货品code
     */
    public function generateGoodsCode() {
        $code = substr('G'.md5(microtime(true)),0,9);
        $sql = "select id from r_goods where code = '$code'";
        $id = $this->erpManageDb->getOne($sql);
        if ($id) {
            return $this->generateGoodsCode();
        }
        return $code;
    }
    /**
     * 追加规格商品 入库增加数量(补货)
     */
    public function setGoodsStockNum($pid,$gid,$stockNum,$price) {
        $sql = "update r_goods set stock_into_num=stock_into_num+$stockNum,real_stock_num=real_stock_num+$stockNum where id=$gid";
        $re = $this->erpManageDb->update($sql);//更新规格商品数量，价格
        if (!$re) return false;
        $this->addProductStockNum($pid,$stockNum);//更新货品库存
        return $this->addStockIntoDetail($pid,$gid,$stockNum,$price); //新增入库明细
    }

    /**
     * 盘点更新 真实库存 数量
     */
    public function setGoodsRealStockNum($pid,$gid,$stockNum) {
        $sql = "update r_goods set real_stock_num=$stockNum where id=$gid";
        $r = $this->erpManageDb->update($sql);
        if (!$r) return false;
        return $this->repeatProductRealStockNum($pid);//更新货品总真实库存
    }

    /**
     * 查询全部规格商品的真实数量
     */
    public function getStandGoodsRealStockNum($pid) {
        $sql = "select sum(`real_stock_num`) as cnt from r_goods where product_id=$pid and status=0";
        return $this->erpManageDb->getOne($sql);
    }

    /**
     * 赛事或其他业务模块 查询规格商品
     */
    public function getGoodsListByProductCode($pcode, $type=2) {
        if ($type == 1) {
            $info = $this->getProductInfo($pcode, 'id,title,status');//查询货品通过ID
        } else {
            $info = $this->getProductInfoByCode($pcode, 'id,title,status');//查询货品通过CODE
        }
        if (!$info) return false;
        $sql = "select image_url from  r_product_image where product_id={$info['id']} and status=0";
        $imageUrl = $this->erpManageDb->getOne($sql);
        $info['imageUrl'] = $imageUrl ? $imageUrl : '';
        $info['childGoods']= [];
        $sql = "select * from r_goods where product_id={$info['id']}";
        $list = $this->erpManageDb->getAll($sql);
        if (!$list) {
            return $info;
        }
        $arrStockInto = $this->getStockIntoList($info['id']);
        $firstCostArr = [];
        foreach($arrStockInto as $row){
            $firstCostArr[$row['goods_id']] = $row['price'];
        }
        
        $result = [];
        foreach($list as $key=>$val) {
            $result[$key]['gid'] = $val['id'];
            $result[$key]['attrPathName'] = $this->getAttrPathName($val['product_id'],$val['attr_path']);
            $result[$key]['realStockNum'] = $val['real_stock_num'];
            $result[$key]['price'] = $val['price'];
            $result[$key]['firstCost'] = $firstCostArr[$val['id']];
        }
        $info['childGoods'] = $result;
        return $info;
    }

    /**
     * 后台补货等模块 查询规格商品
     */
    public function getGoodsListByProductMixed($pcode, $type=2) {
        if ($type == 1) {
            $info = $this->getProductInfo($pcode, 'id,title');//查询货品通过ID
        } else {
            $info = $this->getProductInfoByCode($pcode, 'id,title');//查询货品通过CODE
        }
        if (!$info) return false;
        $sql = "select image_url from  r_product_image where product_id={$info['id']}";
        $imageUrl = $this->erpManageDb->getOne($sql);
        $info['imageUrl'] = $imageUrl ? $imageUrl : '';
        $info['childGoods']= [];
        $sql = "select * from r_goods where product_id={$info['id']}";
        $list = $this->erpManageDb->getAll($sql);
        if (!$list) {
            return $info;
        }
        $result = [];
        foreach($list as $key=>$val) {
            $result[$key]['gid'] = $val['id'];
            $result[$key]['attrPathName'] = $this->getAttrPathName($val['product_id'],$val['attr_path']);
            $result[$key]['realStockNum'] = $val['real_stock_num'];
        }
        $info['childGoods'] = $result;
        return $info;
    }

    /**
     * 库存商品卖出
     */
    public function saleGoods($gid,$saleNum=1) {
        $sql = "update r_goods set sale_num=sale_num+$saleNum,real_stock_num=real_stock_num-$saleNum where id=$gid";
        $r = $this->erpManageDb->update($sql);
        $r2 = false;
        if ($r) {
            //查询货品
            $arrProduct = $this->getGoodsInfo($gid,$fields ='product_id');
            if ($arrProduct) {
                $sql = "update r_product set sale_num=sale_num+$saleNum,real_stock_num=real_stock_num-$saleNum where id={$arrProduct['product_id']}";
                $r2 = $this->erpManageDb->update($sql);
            }
        }
        if ($r && $r2) {
            //记录全局操作日志
            $this->addErpLog(1,$arrProduct['product_id'],2,'货品ID：'.$arrProduct['product_id'].' 售出'.$saleNum.' 件,规格商品ID：'.$gid);
        }
        return $r;
    }

    /*****************************商品END**********************************/

    /*****************************盘点START**********************************/
    /**
     * 盘点
     * @param $pid   货品ID
     * @param $currentStockNum  货品当前库存
     * @param $gid  规格商品ID
     * @param $realStockNum  盘点的实际库存
     * @param $content 盘点备注
     * @return bool|mixed
     */
    public function checkStock($pid,$currentStockNum,$gid,$realStockNum,$content) {
        $re = $this->addCheckStockDetail($pid,$gid,$currentStockNum,$realStockNum,$content);//记录盘点详情
        if (!$re) {
            return false;
        }
        $re = $this->setGoodsRealStockNum($pid,$gid,$realStockNum); //修正规格商品和货品的真实库存
        return $re;
    }

    /**
     * 记录盘点详情
     * @param $pid
     * @param $currentStockNum
     * @param $realStockNum
     * @param $content
     * @return mixed
     */
    public function addCheckStockDetail($pid,$gid,$currentStockNum,$realStockNum,$content) {
        //记录盘点信息
        $data = array(
            'product_id'=>$pid,
            'goods_id'=>$gid,
            'current_stock_num'=>$currentStockNum,
            'real_stock_num'=>$realStockNum,
            'content'=>$content,
            'operate_uid'=>$this->base->realUser['uid'],
            'create_time'=>time()
        );
        $r = $this->erpManageDb->insertRow('r_stock_check_detail',$data,0);
        return $r;
    }
    /*****************************盘点END**********************************/

    /*****************************入库明细START**********************************/
    /**
     * 增加入库明细
     */
    public function addStockIntoDetail($pid,$gid,$num,$price) {
        $data = array(
            'product_id'=>$pid,
            'goods_id'  =>$gid,
            'stock_into_num'=>$num,
            'price'=>$price,
            'operate_uid'=>$this->base->realUser['uid'],
            'create_time'=>time()
        );
        $r = $this->erpManageDb->insertRow('r_stock_into_detail',$data,0);
        return $r;
    }
    /*****************************入库明细END**********************************/

    /*****************************业务商品START**********************************/
    /**
     * 生成业务对象商品
     * @param $type  对象类型: 1 赛事 5 闪购
     * @param $object_id  对象ID（赛事/闪购等）
     * @param $product_id  货品ID
     * @param $stand_id   规格商品ID
     * @param $stock_num   库存数量
     * @param $sale_price   售价
     * @return mixed
     */
    public function addObjectGoods($type,$object_id,$product_id,$stand_good_id,$stock_num,$sale_price,$sort=0) {
        $create_time = time();
        $data = compact('type','object_id','product_id','stand_good_id','stock_num','sale_price','create_time','sort');
        return $this->erpManageDb->insertRow('r_object_goods',$data,0);
    }

    /**
     *查询后台业务商品列表
     */
    public function getObjectGoodsList($objectId,$type,$fields='*') {
        $sql  = "select $fields from r_object_goods where object_id=$objectId and type=$type and status=0 order by create_time desc";
        return  $this->erpManageDb->getAll($sql);
    }

    /**
     * 查询是否存在业务商品
     */
    public function getIsExistGoodsByObjectId($objectId,$type) {
        $sql  = "select count(1) from r_object_goods where object_id=$objectId and type=$type and status=0 limit 1";
        return  $this->erpManageDb->getOne($sql) ? true : false;
    }

    /**
     * 删除业务商品
     * @param $objectId
     * @param $pid
     * @param int $standGoodId
     * @return mixed
     */
    public function saveObjectStatus($type, $objectId, $pid = 0, $standGoodId = 0) {
        $where = "object_id=$objectId  and type=$type";
        if ($pid) {
            $where .=" and product_id=$pid";
        }
        if ($standGoodId) {
            $where .=" and stand_good_id=$standGoodId";
        }
        $sql = "update r_object_goods set status = -5 where $where";
        return $this->erpManageDb->update($sql);
    }

    /**
     * 查询业务的某个货品规格商品的信息
     * @param $id  业务商品主ID
     * @return mixed
     */
    public function getObjectGoodsInfo($id) {
        $sql = "select * from r_object_goods where id=$id";
        $info = $this->erpManageDb->getRow($sql);
        return $info;
    }

    /**
     * 售出业务商品
     * @param $id  业务商品ID
     * @param int $num  售出数量
     * @return mixed
     */
    public function saleObjectGoods($id, $num=1) {
        $sql = "update r_object_goods set sale_num=sale_num+$num where id=$id";
        $r = $this->erpManageDb->update($sql);
        if ($r) {
            $info = $this->getObjectGoodsInfo($id);//查询商品归属的业务类型
            if ($info['type'] == 5) {
                $this->base->load('flashBuy')->saleFlashGoods($info['object_id'],$num);//售出闪购商品，总数量减少,给定时器下架闪购提供参考
            }
         //业务商品操作日志
        }
        return $r;
    }

    /**
     * 订单超时未付款，库存回滚
     * @param $id  业务商品ID
     * @param int $num  回滚数量
     * @return mixed
     */
    public function rollbackObjectGoodsSaleNum($id, $num=1) {
        $sql = "update r_object_goods set sale_num=sale_num-$num where id=$id";
        $r = $this->erpManageDb->update($sql);
        if ($r) {
            $info = $this->getObjectGoodsInfo($id);//查询商品归属的业务类型
            if ($info['type'] == 5) {
                $this->base->load('flashBuy')->rollbackFlashGoodsSaleNum($info['object_id'],$num);//售出闪购商品，总数量减少,给定时器下架闪购提供参考
            }
        }
        return $r;
    }


    /**
     * 查询业务商品关联的货品信息
     */
    public function getProductInfoByObjectId($objectId,$fields='*',$type=5) {
        $where = "object_id=$objectId and type=$type";
        $productIdList = $this->erpManageDb->getAll("select DISTINCT product_id from r_object_goods where $where");
        $result = [];
        if (!$productIdList)  return $result;
        foreach ($productIdList as $key=>$val) {
            $result[] = $this->getProductInfo($val['product_id'],$fields);
        }
        return  $result;
    }
    /*****************************业务商品END**********************************/

    /*****************************订单导入START**********************************/

    /**
     * 生成导入记录
     * @param $params totalNum:总条数   successNum：成功条数 excelUrl：excel地址
     * @return mixed
     */
    public function addOrderImport($params) {
        $data = array(
            'total_num'=>$params['totalNum'],
            'success_num'=>$params['successNum'],
            'operate_uid'=>$this->base->realUser['uid'],
            'create_time'=>time(),
            'excel_url'=>$params['excelUrl']);
        $r = $this->erpManageDb->insertRow('r_order_import',$data,0);
        return $r;
    }

    /**
     * 更新导入记录
     * @param $params  id 导入ID   successNum：成功条数
     * @return mixed
     */
    public function saveOrderImport($params) {
        $id =$params['id'];
        $successNum = (int)$params['successNum'];
        $updateTime = time();
        $sql = "update r_order_import set success_num=$successNum,update_time=$updateTime where id=$id";
        $r = $this->erpManageDb->update($sql);
        return $r;
    }

    /**
     * 生成订单导入明细
     * @param $params  importId :导入ID   orderId：订单编号 reason:失败原因 status: 状态（-5：失败 0 成功）
     * @return mixed
     */
    public function addOrderImportDetail($params) {
        $data = array(
            'import_id'=>$params['importId'],
            'order_id'=>$params['orderId'],
            'reason'=>$params['reason'],
            'create_time'=>time(),
            'status'=>$params['status']);
        $r = $this->erpManageDb->insertRow('r_order_import_detail',$data,0);
        return $r;
    }

    /**
     * 查询导入记录
     * @param $params
     * @return mixed
     */
    public function getImportOrderList($params) {
        $start    = $params['start'] ? (int)$params['start'] : 0;
        $limitNum = $params['limit'] ? (int)$params['limit'] : 10;
        $where = 1;
        $sql ="select * from r_order_import where $where order by id desc limit $start,$limitNum";
        $cntsql ="select count(1) as cnt from r_order_import where $where";
        $this->total =  $this->erpManageDb->getOne("$cntsql");
        return $this->erpManageDb->getAll($sql);
    }

    /**
     * 查询导入记录明细
     * @param $importId   导入ID
     * @param $params
     * @return mixed
     */
    public function getImportOrderDetail($importId,$params) {
        $start    = $params['start'] ? (int)$params['start'] : 0;
        $limitNum = $params['limit'] ? (int)$params['limit'] : 10;
        $where = 'import_id='.$importId;
        $sql ="select * from r_order_import_detail where $where order by id desc limit $start,$limitNum";
        $cntsql ="select count(1) as cnt from r_order_import_detail where $where";
        $this->total =  $this->erpManageDb->getOne("$cntsql");
        return $this->erpManageDb->getAll($sql);
    }


    /*****************************订单导入END**********************************/


    /*****************************全局操作日志START**********************************/
    /**
     * 增加全局操作日志
     * @param $operateType 操作类别 1 增加 2 更新  3 删除
     * @param $objectId  对象ID
     * @param $objectType 对象类型 1 订单 2 货品 3 物流模板 4 分类
     * @param $content   操作详情
     */
    public function addErpLog($operateType,$objectId,$objectType,$content) {
        if (!in_array($objectType,[1,2,3,4])) {
            return false;
        }
        $data = array(
            'operate_uid'=>$this->base->realUser['uid'],
            'object_id'=>$objectId,
            'object_type'=>$objectType,
            'content'=>$content,
            'operate_type'=>$operateType,
            'operate_time'=>time()
        );
        $this->base->in_logDb()->insertRow('r_erp_operate_log',$data,0);
    }
    /*****************************全局操作日志END**********************************/


}